package cn.yqx.bankshop.goods.service.impl;

import cn.yqx.bankshop.goods.dao.BuProductTypeMapper;
import cn.yqx.bankshop.goods.pojo.BuProductType;
import cn.yqx.bankshop.goods.pojo.BuProductTypeExample;
import cn.yqx.bankshop.goods.service.IndexService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class IndexServiceImpl implements IndexService {
    private static  final   int  IS_ENABLE = 1 ;
    @Autowired
    BuProductTypeMapper buProductTypeMapper ;

    @Override
    public List<BuProductType> getProductList(int grade,Long parProductId){
        List<BuProductType> list = new ArrayList<BuProductType>() ;
        BuProductTypeExample example = new BuProductTypeExample() ;

        if( parProductId != null ){
            example.or().andGradeEqualTo(grade).andEnabledEqualTo(IS_ENABLE).andParProductIdEqualTo(parProductId) ;
        }else{
            example.or().andGradeEqualTo(grade).andEnabledEqualTo(IS_ENABLE) ;
        }

        return buProductTypeMapper.selectByExample(example) ;
    }

    @Override
    public JSONArray getProductSonList(Long parProductId) {
        JSONArray jsonArray = new JSONArray( );
        BuProductTypeExample example = new BuProductTypeExample() ;
        example.or().andParProductIdEqualTo(parProductId) ;
        List<BuProductType> list = buProductTypeMapper.selectByExample(example) ;

        if(!list.isEmpty()){
            list.stream().forEach((item) ->{
                BuProductTypeExample exampleSon = new BuProductTypeExample() ;
                exampleSon.or().andParProductIdEqualTo(item.getId()) ;
                JSONObject json;
                List<BuProductType> listSon = buProductTypeMapper.selectByExample(exampleSon) ;
                json = (JSONObject) JSONObject.toJSON(item);
                json.put("sonProductList",listSon) ;
                jsonArray.add(json);
            });

        }

        return jsonArray;
    }


}
